package com.amxing.spider.task;


import com.amxing.spider.listener.NullListener;
import com.amxing.spider.listener.task.BatchTaskListener;
import com.amxing.spider.task.support.BatchTask;
import com.amxing.spider.utils.AppConfig;
import com.amxing.spider.utils.SpringContextHolder;
import com.amxing.spider.utils.StringUtil;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;

/**
 * @auther amxing
 * @desc
 * @createTime 2018/8/12 14:17
 */
public interface Task<T> extends Runnable {

    String uuid = StringUtil.getUUID();

    AppConfig config = SpringContextHolder.getBean(AppConfig.class);

    default String getUUID() {
        return uuid;
    }

    static Task createTask(String url, TaskQueue<Class<? extends Task>> strategy) {
        return createTask(url, null, strategy);
    }

    static Task createTask(String url, TaskCache taskCache, TaskQueue<Class<? extends Task>> strategy) {
        if (strategy == null || strategy.isEmpty())
            return null;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(strategy.poll());
        enhancer.setCallbackFilter(method -> method.getName().equals("run") ? 1 : 0);
        enhancer.setCallbacks(new Callback[]{new NullListener(),new BatchTaskListener(strategy)});
        return (Task) enhancer.create(new Class[]{String.class, TaskCache.class}, new Object[]{url, taskCache});
    }

    static Task copyTask(String url, Class<? extends BatchTask> c, TaskQueue<Class<? extends Task>> strategy) {
        if (strategy == null || strategy.isEmpty())
            return null;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(c);
        enhancer.setCallbackFilter(method -> method.getName().equals("run") ? 1 : 0);
        enhancer.setCallbacks(new Callback[]{new NullListener(),new BatchTaskListener(strategy)});
        return (Task) enhancer.create(new Class[]{String.class, TaskCache.class}, new Object[]{url, null});
    }

}
